import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Upload, Input, Drawer } from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProForm, { ModalForm, DrawerForm, ProFormText, ProFormSelect, ProFormTextArea } from '@ant-design/pro-form';
import ProDescriptions from '@ant-design/pro-descriptions';
import CSV from '../../components/csv';
import api from '@/services/ant-design-pro/api';
import FileSaver from 'file-saver'
import { reject, toInteger } from 'lodash';
import { generateForm, castType } from '../generateForm'
import ChoosePage from './components/ChoosePage';
import ChoosenPage from './components/ChoosenPage';

const fromTimeRange = (row) => {
  if ('timeRange' in row) {
    row = { ...row, begin_time: row['timeRange'][0], end_time: row['timeRange'][1] }
    if (!(row.begin_time instanceof Number) && !isNaN(Date.parse(row.begin_time))) {
      row.begin_time = Date.parse(row.begin_time)
    }

    if (!(row.end_time instanceof Number) && !isNaN(Date.parse(row.end_time))) {
      row.end_time = Date.parse(row.end_time)
    }
    delete row['timeRange']
  }

  console.log(row)
  return row
}

const toTimeRange = (rows) => {
  console.log(rows)
  const res = rows.map(row => { row.timeRange = [row.begin_time, row.end_time]; return row; })
  console.log(res)
  return res
}

const getActivity = async (params, options) => {
  let result = await api.activity(fromTimeRange(params), options)
  result.data = toTimeRange(result.data)
  return result
}

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await api.removeactivity(selectedRows.map((row) => row.id));
    hide();
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};

const activityList = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */

  const [updateChoosePageVisible, handleUpdateChoosePageVisible] = useState(false);
  const [updateChoosenPageVisible, handleUpdateChoosenPageVisible] = useState(false);

  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const intl = useIntl();
  const columns = [
    {
      title:
        (
          <FormattedMessage
            id="pages.activity.name"
          />
        ),
      dataIndex: 'name',
      render: (dom, entity) => {
        return (
          entity.active == 1 ?
            <a
              onClick={() => {
                console.log(entity)
                setCurrentRow(entity)
                handleUpdateChoosePageVisible(true)
              }}
            >
              {dom}
            </a> : <>{dom}</>
        );
      },
    },
    {
      title:
        <FormattedMessage id="pages.activity.active" defaultMessage="active" />,
      dataIndex: 'active',
      ignore: true,
      valueEnum: {
        0: {
          text: <FormattedMessage id="pages.activity.deactivate" defaultMessage="deactivate" />,
          status: '0',
        },
        1: {
          text: <FormattedMessage id="pages.activity.activate" defaultMessage="active" />,
          status: '1',
        }
      }
      //valueType: 'textarea',
    },
    {
      title:
        <FormattedMessage id="pages.activity.timeRange" defaultMessage="timeRange" />,
      dataIndex: 'timeRange',
      valueType: 'dateTimeRange',
    },
    {
      title:
        <FormattedMessage id="pages.activity.userSelectCnt" defaultMessage="userSelectCnt" />,
      dataIndex: 'user_select_cnt',
      valueType: 'digit',
      //valueType: 'textarea',
    },
    {
      title:
        <FormattedMessage id="pages.activity.choose_limit" defaultMessage="choose_limit" />,
      dataIndex: 'choose_limit',
      valueType: 'digit',
      //valueType: 'textarea',
    },
    {
      title:
        <FormattedMessage id="pages.activity.grade" defaultMessage="grade" />,
      dataIndex: 'grade',
      //valueType: 'textarea',
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [

        <Button key='seeChoosen' type="primary" shape="round" size='large'
          onClick={() => {
            console.log(record)
            setCurrentRow(record)
            handleUpdateChoosenPageVisible(true)
          }}>
          <FormattedMessage id="pages.activity.seeChoosen" defaultMessage="See Choosen" />
        </Button>
      ],
      ignore: (true)
    },
  ];

  const IntlText = function (e) {
    return intl.formatMessage({
      id: e.props.id,
    })
  }

  return (
    <PageContainer>
      <ProTable
        headerTitle={intl.formatMessage({
          id: 'menu.list.activity-list',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        request={getActivity}
        columns={columns}
        pagination={{ pageSizeOptions: [10, 20, 50, 100, 500, 1000] }}
      />

      <ChoosePage
        ActivityID={currentRow ? currentRow.id : null}
        updateChoosePageVisible={updateChoosePageVisible}
        onCancel={() => {
          handleUpdateChoosePageVisible(false)
          setCurrentRow(null)
        }} />

      <ChoosenPage
        ActivityID={currentRow ? currentRow.id : null}
        updateChoosenPageVisible={updateChoosenPageVisible}
        onCancel={() => {
          handleUpdateChoosenPageVisible(false)
          setCurrentRow(null)
        }} />

    </PageContainer>
  );
};

export default activityList;
